<!-- 文件上传 -->
<template>
  <a-upload
    :key="key"
    ref="upload"
    :multiple="true"
    :default-file-list="defaultFileList"
    :action="uploadApi.apk"
    :headers="headers"
    accept=".doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf"
    @change="handleChange"
    :showUploadList="{
      showRemoveIcon: !disabled
    }"
  >
    <a-button v-if="fileList.length < (maxNum || 1)" type="primary" :disabled="disabled">
      <a-icon type="upload" /> {{ btnText }}
    </a-button>
  </a-upload>
</template>

<script>
import { uploadApi } from '@/api/upload'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import { buildUUID } from '@/utils/uuid'
import { cloneDeep } from 'lodash-es'

export default {
  props: {
    defaultFileList: {
      required: false,
      // type: Array,
      default: () => []
    },
    // fileList: {
    //   required: false,
    //   type: Array,
    //   default: () => [],
    // },
    disabled: {
      required: false,
      type: Boolean,
      default: () => false
    },
    btnText: {
      required: false,
      type: String,
      default: () => '上传附件'
    },
    maxNum: {
      required: false,
      type: Number,
      default: () => 3
    }
  },
  components: {},
  watch: {
    defaultFileList: {
      handler(v) {
        if (v.length) {
          this.$nextTick(() => {
            this.key = Date.now()
          })
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      uploadApi,
      headers: {
        token: Vue.ls.get(ACCESS_TOKEN),
        tenantId: Vue.ls.get(TENANTID)
      },
      loading: false,
      fileList: [],
      key: Date.now()
    }
  },
  methods: {
    handleChange(info) {
      let fileList = [...info.fileList]

      let files = []
      for (let i = 0; i < fileList.length; i++) {
        const file = fileList[i]

        if (file.status === 'done') {
          let names = file.name.split('.') || []
          files.push({
            uid: buildUUID(),
            status: 'done',
            name: file.name,
            url: file.url || file.response.data.fileUrl,
            size: file.size,
            fileType: file.fileType || names[names.length - 1]
          })
        }
      }
      this.fileList = files

      this.$emit('uploadSuccess', files)
    }
  },
  created() {
    this.fileList = cloneDeep(this.defaultFileList)
  },
  mounted() {}
}
</script>
<style scoped></style>
